package com.nowcoder.controller;

import com.nowcoder.entity.Message;
import com.nowcoder.entity.Page;
import com.nowcoder.entity.User;
import com.nowcoder.service.MessageService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.HostHolder;
import com.nowcoder.utils.NowCoderUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.Oneway;
import java.util.*;

/**
 * @Author liujilong
 * @Project nowcoder
 * @File MessageController
 * @Date 2022/1/19 2:38 下午
 **/
@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page) {
        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.selectConversationCount(user.getUid()));

        List<Message> conversationList = messageService.selectConversations(user.getUid(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("letterCount", messageService.selectLetterCount(message.getConversationId()));
                map.put("unreadCount", messageService.selectLetterUnreadCount(user.getUid(), message.getConversationId()));
                String targetUid = user.getUid().equals(message.getFromUid()) ? message.getToUid() : message.getFromUid();
                map.put("target", userService.findByUid(targetUid));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);

        //查询未读消息数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(user.getUid(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.selectLetterCount(conversationId));

        List<Message> letterList = messageService.selectLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findByUid(message.getFromUid()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);
        model.addAttribute("target", getLetterTarget(conversationId));

        List<Integer> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.updateStatus(ids, 1);
        }

        return "/site/letter-detail";
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");

        if (hostHolder.getUser().getUid().equals(ids[0])) {
            return userService.findByUid(ids[0]);
        } else {
            return userService.findByUid(ids[1]);
        }
    }

    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getUser().getUid().equals(message.getToUid()) && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName, String content) {
        User target = userService.selectByName(toName);
        if (target == null) return NowCoderUtil.getJSONString(1, "目标用户不存在");

        Message message = new Message();
        message.setFromUid(hostHolder.getUser().getUid());
        message.setToUid(target.getUid());
        message.setConversationId(message.getFromUid() + "_" + message.getToUid());
        message.setContent(content);
        message.setCreateTime(new Date());

        messageService.insertMessage(message);

        return NowCoderUtil.getJSONString(0);
    }

}
